package com.example.qxfw.nyqx.controller;

import cn.hutool.core.date.DateTime;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.ny.CropGrowdateFcst;
import com.example.qxfw.common.entity.ny.CropyieldFcst;
import com.example.qxfw.common.entity.ny.StationInfo;
import com.example.qxfw.nyqx.dto.FyqybParamDto;
import com.example.qxfw.nyqx.service.*;
import com.example.qxfw.nyqx.vo.GrowdateFcstListVo;
import com.example.qxfw.nyqx.vo.GrowdateHistoryListVo;
import com.example.qxfw.rcyw.service.StationInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "农气预报-发育期预报")
@RestController
@CrossOrigin
@RequestMapping("/DevelopmentPeriodPredictionController")
public class DevelopmentPeriodPredictionController {

    @Value("${filePath.active}")
    private String active;

    @Autowired
    private DevelopmentPeriodPredictionService developmentPeriodPredictionService;

    @Autowired
    private CropGrowdateFcstService growdateFcstService;

    @Autowired
    private CropGrowdateHistoryService cropGrowdateHistoryService;


    @Autowired
    private StationInfoService stationInfoService;

    @Autowired
    private CropyieldFcstService cropyieldFcstService;

    @Autowired
    private CropGrowdateIndexlibService cropGrowdateIndexlibService;


    @ApiOperation("获取作物名称")
    @GetMapping("/getGrowDateCropName")
    public SysResult getGrowDateCropName() {
        List<String> cropName = cropGrowdateIndexlibService.getCropName();
        return SysResult.success(cropName);
    }

    @ApiOperation("根据作物名称获取种类")
    @GetMapping("/getGrowDateCropType")
    public SysResult getGrowDateCropType(String cropName) {
        List<String> type = cropGrowdateIndexlibService.getType(cropName);
        return SysResult.success(type);
    }


    @ApiOperation("获取农服站点")
    @GetMapping("/getAgriStation")
    public SysResult getAgriStation(String mainCrop) {
        List<StationInfo> stationInfos = developmentPeriodPredictionService.listByMainCrop(mainCrop);
        return SysResult.success(stationInfos);
    }

    @ApiOperation("获取发育期")
    @GetMapping("/getAgriGrowdate")
    public SysResult getAgriGrowdate(String mainCrop) {
        List<String> stationInfos = cropGrowdateIndexlibService.getGrowDateName(mainCrop);
        return SysResult.success(stationInfos);
    }

    @ApiOperation("预报制作")
    @PostMapping("/ybzz")
    public SysResult ybzz(@RequestBody FyqybParamDto fyqybParamDto) {
        String date = developmentPeriodPredictionService.ybzz(fyqybParamDto);
        if (date == null) {
            return SysResult.fail("上一个发育期时间为空");
        } else {
            return SysResult.success(date);

        }
    }

    @ApiOperation("预报查询-获取预报列表数据")
    @GetMapping("/getYbList")
    public SysResult getYbList(String cropName, String type, String growName, long year) {
        List<CropGrowdateFcst> growdateFcstListVos = growdateFcstService.getList3(year, cropName, type, growName);
        for (CropGrowdateFcst fcst : growdateFcstListVos) {
            StationInfo info = stationInfoService.getById(fcst.getStationid());
            List<String> yields = cropyieldFcstService.getYield(fcst.getStationid(),year,cropName,type);
            fcst.setStationname(info.getStationname());
            if (yields == null && yields.isEmpty()){
                fcst.setYield(yields.get(0));
            }else {
                fcst.setYield(null);
            }
           // fcst.setYield(yields.get(0));
        }
        return SysResult.success(growdateFcstListVos);
    }

    @ApiOperation("预报制作-获取分析统计数据")
    @GetMapping("/getHistoryList")
    public SysResult getHistoryList(long year1, long year2, String stationId, String type, String cropName, String growDateName) {
        //预报
        List<GrowdateFcstListVo> growdateFcstListVos = growdateFcstService.listByYear(year1, year2, stationId, type, cropName, growDateName);
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
        List<GrowdateFcstListVo> listfst = growdateFcstListVos.stream().map(
                i -> {
                    GrowdateFcstListVo bo = new GrowdateFcstListVo();
                    BeanUtils.copyProperties(i, bo);
                    String value = sdf.format(bo.getForecastdate());
                    bo.setValue(value);
                    return bo;
                }
        ).collect(Collectors.toList());


        //历史
        List<GrowdateHistoryListVo> growdateHistoryListVos = cropGrowdateHistoryService.getList(year1, year2, stationId, type, cropName, growDateName);
        List<GrowdateHistoryListVo> listmsg = growdateHistoryListVos.stream().map(
                i -> {
                    GrowdateHistoryListVo bo = new GrowdateHistoryListVo();
                    BeanUtils.copyProperties(i, bo);
                    String value = sdf.format(bo.getGrowdatedate());
                    bo.setValue(value);
                    return bo;
                }
        ).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("fcst", listfst);
        map.put("history", listmsg);
        List<String> strArrTime = new ArrayList<>();
        if (listmsg.size() > 0 || listfst.size() > 0) {
            for (int i = 0; i < listmsg.size(); i++) {
                strArrTime.add(listmsg.get(i).getValue());
            }
            for (int j = 0; j < listfst.size(); j++) {
                strArrTime.add(listfst.get(j).getValue());
            }
        }

        map.put("min", Collections.min(strArrTime));
        map.put("max", Collections.max(strArrTime));
        return SysResult.success(map);
    }


    /**
     * 发育期预报
     *
     * @param YXJW       有效积温
     * @param PJWD       平均积温
     * @param fyqTime    发育期时间
     * @param temp       温度下限
     * @param NSZstation 站点名称
     * @param fyqName    发育期名称
     * @param time       年份
     * @param type       品种
     * @param cropsName  农作物名称
     * @return
     */
    @ApiOperation("农气预报-发育期预报-产品生成")
    @GetMapping(value = "CropGrowdateforecast")
    public Object cropGrowdateforecast(String YXJW, String PJWD, String fyqTime,
                                       @RequestParam(value = "temp",required = false,defaultValue = "0") Integer temp, String NSZstation, String fyqName,
                                       String time, String type, String cropsName, String maker) {
        DateTime datenow = DateTime.now();
        String year = String.valueOf(datenow.year());
        String month = String.valueOf(datenow.month());
        String day = String.valueOf(datenow.dayOfMonth());
        return developmentPeriodPredictionService.cropGrowdateforecast(year, month, day, YXJW,
                PJWD, fyqTime, temp, NSZstation, fyqName, time, type, cropsName, maker);
    }

    @ApiOperation("获取产品模板")
    @GetMapping("/getTemplate")
    public Object getTemplate() {
        //模板路径
        String templatePath;
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        if (active.equals("dev")) {
            templatePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath() +
                    "\\src\\main\\resources\\templates\\nqfwTemp\\发育期预报.docx";
        } else {
            templatePath = applicationHome.getSource().getParentFile() +
                    "\\resource\\templates\\nqfwTemp\\发育期预报.docx";
        }
        // 设置前端响应
        byte[] buffer = new byte[1024];
        int bytesRead;
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                FileInputStream inputStream = new FileInputStream(templatePath);
        ) {
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment", "发育期预报.docx");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentLength(byteArray.length);
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (Exception e) {
            System.err.println("模板下载失败");
        }
        return null;
    }


}
